<!-- 会议详情页 -->
<template>
  <div class="meeting-detail">
    <!-- 手机端样式 -->
    <div v-if="isMobile" class="mobile-detail">
      <div class="mobile-header">
        <div class="mobile-header-row">
          <a-button type="text" class="mobile-back-btn" @click="goBack">
            <img src="@/assets/icons/wecom-left.svg" alt="返回" class="back-svg" />
          </a-button>
          <a-dropdown v-if="isCreator" trigger="click" @select="handleMenuSelect">
            <div class="menu-btn">
              <img src="@/assets/icons/menu-three.svg" alt="更多" class="more-vertical-svg" />
            </div>
            <template #content>
              <a-doption v-if="isCreator && canEditMeeting" value="edit">编辑会议</a-doption>
              <a-doption v-if="isCreator && meetingInfo?.circleType === 1" value="editSub">编辑子会议</a-doption>
              <a-doption v-if="isCreator" value="cancel" class="danger">取消会议</a-doption>
            </template>
          </a-dropdown>
        </div>
      </div>
      <div class="subject subject-center mobile-title">{{ meetingInfo?.subject }}</div>
      <div class="mobile-content">
        <div class="row time-row" style="color:#222;">
          <IconCalendar style="margin-right:6px;color:#2E71FF" />
          <span>{{ getMobileTime(meetingInfo?.startTime, meetingInfo?.endTime) }}</span>
        </div>
        <!-- 周期会议信息移动到日期下方 -->
        <div v-if="meetingInfo?.cycleEndDate || meetingInfo?.cycle" class="cycle-info-row">
          <span>{{ meetingInfo?.subInfo || getCycleInfo() }}</span>
          <span v-if="meetingInfo?.cycleEndDate" style="margin-left: 8px; color: #888;">{{ formatMobileCycleEnd(meetingInfo.cycleEndDate) }}</span>
        </div>
        <!-- 线下会议地点展示 -->
        <div v-if="meetingInfo?.meetType === 0 && meetingInfo?.location" class="location-info-row">
          <span class="location-label">会议地点：</span>
          <span class="location-value">{{ meetingInfo.location }}</span>
        </div>
        <div class="row creator-row">
          <span class="creator-label">发起人：</span>
          <img v-if="meetingInfo?.participants?.[0]?.avatar" :src="meetingInfo.participants[0].avatar" class="avatar" />
          <span class="creator-name">{{ meetingInfo?.createUserName || meetingInfo?.realname }}</span>
        </div>
        <div class="row participants-row" style="cursor: pointer;" @click="showParticipantsModal = true">
          <span class="participants-label">参会人：</span>
          <template v-for="(p, idx) in participantsList.slice(0, maxShowParticipants)" :key="p.userid">
            <img v-if="p.avatar" :src="p.avatar" class="participant-avatar" />
            <span v-if="idx < Math.min(participantsList.length, maxShowParticipants) - 1" style="margin-right:2px;"></span>
          </template>
          <span class="arrow-icon">
            <template v-if="extraCount > 0">
              <IconDoubleRight style="font-size:18px;vertical-align:middle;" />
            </template>
            <span class="participants-total">共{{ participantsList.length }}人</span>
          </span>
          <!-- 参会人弹窗 -->
          <a-modal v-model:visible="showParticipantsModal" title="全部参会人" :footer="false" :closable="true" width="320">
            <div class="participants-modal-list">
              <div v-for="p in participantsList" :key="p.userid" class="modal-participant-item">
                <img v-if="p.avatar" :src="p.avatar" class="participant-avatar" />
                <span class="participant-name">{{ p.realname }}</span>
              </div>
            </div>
          </a-modal>
        </div>
        <div class="row btn-row">
          <a-button class="copy-btn vertical-btn" @click="copyLink">
            <div class="btn-icon-wrap">
              <img src="@/assets/icons/joinLink.svg" class="link-icon" alt="链接" />
            </div>
            <div class="btn-text">复制链接</div>
          </a-button>
          <a-button class="join-btn vertical-btn" @click="joinMeeting">
            <div class="btn-icon-wrap">
              <IconDoubleRight />
            </div>
            <div class="btn-text">进入会议</div>
          </a-button>
        </div>
      </div>
    </div>
    <!-- PC端原有结构 -->
    <div v-else>
    <!-- 头部返回按钮 -->
    <div class="header">
      <a-button type="text" @click="goBack">
        <template #icon>
          <icon-arrow-left />
        </template>
        <template #default>返回</template>
      </a-button>
      <div class="title">会议详情</div>
    </div>

    <!-- 会议信息内容 -->
    <div class="content">
      <a-spin :loading="loading">
        <div v-if="meetingInfo" class="meeting-info">
          <div class="info-header">
            <div class="name">{{ meetingInfo.subject }}</div>
            <div class="status" :class="[`status-${meetingInfo.conferenceState}`]">
              {{ getConferenceState(meetingInfo.conferenceState) }}
            </div>
          </div>

          <div class="info-item">
            <div class="item-label">会议时间</div>
            <div class="item-value">{{ getTime(meetingInfo.startTime) }} - {{ getTime(meetingInfo.endTime) }}</div>
          </div>

          <div class="info-item">
            <div class="item-label">发起人</div>
            <div class="item-value">{{ meetingInfo.createUserName || meetingInfo.realname }}</div>
          </div>

          <div class="info-item">
            <div class="item-label">参会人</div>
            <div class="item-value">{{ getParticipantStr(meetingInfo.participants) }}</div>
          </div>

          <div v-if="meetingInfo.meetType === 0 && meetingInfo.location" class="info-item">
            <div class="item-label">地点</div>
            <div class="item-value">{{ meetingInfo.location }}</div>
          </div>

          <div v-if="meetingInfo.meetType === 0 && meetingInfo.meetingRoomName" class="info-item">
            <div class="item-label">会议室</div>
            <div class="item-value">{{ meetingInfo.meetingRoomName }}</div>
          </div>

          <div v-if="meetingInfo.cycleEndDate" class="info-item">
            <div class="item-label">周期</div>
            <div class="item-value">
              {{ meetingInfo.subInfo || getCycleInfo() }}
              <template v-if="meetingInfo.cycleEndDate">(直到 {{ formatDate(meetingInfo.cycleEndDate) }} 结束)</template>
            </div>
          </div>

          <!-- 会议操作按钮 -->
          <div class="action-buttons">
            <a-button type="primary" @click="joinMeeting">
              <template #icon>
                  <IconDoubleRight />
              </template>
              <template #default>进入会议</template>
            </a-button>
            <a-button @click="copyLink">
              <template #icon>
                <img src="@/assets/icons/joinLink.svg" class="link-icon" alt="链接" />
              </template>
              复制链接
            </a-button>
            <!-- 仅会议创建者可见的按钮 -->
            <template v-if="isCreator && canEditMeeting">
              <a-button @click="editMeeting">
                <template #icon><icon-edit /></template>
                编辑会议
              </a-button>
              <a-button status="danger" @click="showCancelConfirm">
                <template #icon><icon-delete /></template>
                取消会议
              </a-button>
            </template>
          </div>
        </div>
        <div v-else-if="!loading" class="no-data">
          <a-empty>
            <template #image>
              <img src="@/assets/images/icon_empty.png" alt="empty" />
            </template>
            <template #default>会议不存在或已被取消</template>
          </a-empty>
        </div>
      </a-spin>
      </div>
    </div>
  </div>

  <!-- 移动端子会议管理模态框 -->
  <a-modal
    v-model:visible="showSubMeetingModal"
    title="子会议管理"
    :footer="false"
    :closable="true"
    width="90%"
    style="max-width: 400px;"
  >
    <div v-if="subMeetingList.length" class="mobile-sub-meeting-list">
      <div v-for="sub in subMeetingList" :key="sub.conferenceId" class="mobile-sub-meeting-item">
        <div class="sub-meeting-header">
          <div class="sub-meeting-title">{{ sub.subject }}</div>
          <div class="sub-meeting-actions">
            <a-button type="text" size="small" @click="editSubMeeting(sub)">编辑</a-button>
            <a-button v-if="subMeetingList.length > 1" type="text" size="small" status="danger" @click="deleteSubMeeting(sub)">删除</a-button>
          </div>
        </div>
        <div class="sub-meeting-info">
          <div class="sub-meeting-time">{{ formatSubMeetingTime(sub.startTime, sub.endTime) }}</div>
          <div class="sub-meeting-promoter">发起人：{{ sub.realname || sub.createUserName }}</div>
        </div>
      </div>
    </div>
    <div v-else class="no-sub-meetings">
      <a-empty description="暂无子会议" />
    </div>
  </a-modal>

  <!-- 移动端编辑子会议模态框 -->
  <a-modal
    v-model:visible="showEditSubModal"
    title="编辑子会议"
    :ok-loading="editSubLoading"
    width="90%"
    style="max-width: 400px;"
    @ok="submitEditSubMeeting"
    @cancel="cancelEditSubMeeting"
  >
    <div class="mobile-edit-sub-form">
      <div class="form-item">
        <div class="form-label">开始时间</div>
        <a-date-picker
          v-model="editSubForm.startTime"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
          placeholder="选择开始时间"
        />
      </div>
      <div class="form-item">
        <div class="form-label">持续时间（分钟）</div>
        <a-input-number
          v-model="editSubForm.length"
          :min="1"
          :max="1440"
          style="width: 100%"
          placeholder="输入持续时间"
        />
      </div>
    </div>
  </a-modal>

  <!-- 移动端编辑会议弹窗 -->
  <a-modal
    v-if="isMobile"
    v-model:visible="showMobileEditPage"
    :width="isMobile ? '95vw' : 600"
    :mask-closable="true"
    :closable="true"
    :footer="false"
    :wrap-class-name="isMobile ? 'mobile-schedule-modal-wrap' : ''"
    title="编辑会议"
    @cancel="closeMobileEditPage"
  >
    <div class="mobile-schedule-content">
      <!-- 主题输入框 -->
      <div class="subject-row-full">
        <input
          v-model="formData.subject"
          placeholder="请输入会议主题"
          maxlength="50"
          class="subject-input-native"
        />
      </div>

      <a-form :model="formData" layout="vertical">
        <div class="form-divider"></div>

        <!-- 参会人选择 -->
        <div class="mobile-form-row">
          <span class="form-label">参会人</span>
          <div class="mobile-attendees-bar" @click="openMobileUserSelector">
            <div class="attendees-avatars">
              <template v-if="selectedUsers.length > 4">
                <span class="attendees-ellipsis">…共{{ selectedUsers.length }}人</span>
                <div v-for="user in selectedUsers.slice(-3)" :key="user.userid" class="attendee-avatar">
                  <img :src="user.avatar || 'https://via.placeholder.com/30'" />
  </div>
              </template>
              <template v-else-if="selectedUsers.length">
                <div v-for="user in selectedUsers" :key="user.userid" class="attendee-avatar">
                  <img :src="user.avatar || 'https://via.placeholder.com/30'" />
                </div>
              </template>
              <template v-else>
                <span class="placeholder-text">请选择参会人</span>
              </template>
            </div>
          </div>
        </div>
        <div class="form-divider"></div>

        <!-- 开始时间 -->
        <div class="mobile-form-row">
          <span class="form-label">开始</span>
          <div class="mobile-start-time-wrapper-left">
            <span class="mobile-date-block-gray" @click.stop="openStartTimePicker(); activePickerTab = 'date'">{{ getStartDateDisplay() }}</span>
            <span class="mobile-time-block-gray" @click.stop="openStartTimePicker(); activePickerTab = 'time'">{{ getStartTimeDisplay() }}</span>
          </div>
        </div>
        <div class="form-divider"></div>

        <!-- 时长 -->
        <div class="mobile-form-row">
          <span class="form-label">{{ formData.isCustomEndTime ? '结束' : '时长' }}</span>
          <div class="mobile-duration-wrapper-left" @click="showDurationModal = true">
            <template v-if="formData.isCustomEndTime">
              <span class="mobile-date-block-gray" @click.stop="showEndTimePicker = true; activeEndPickerTab = 'date'">{{ getEndDateDisplay() }}</span>
              <span class="mobile-time-block-gray" @click.stop="showEndTimePicker = true; activeEndPickerTab = 'time'">{{ getEndTimeDisplay() }}</span>
            </template>
            <template v-else>
              <span class="duration-value">{{ getDurationLabel(formData.durationType) }}</span>
            </template>
          </div>
        </div>
        <div class="form-divider"></div>

        <!-- 地点选择 -->
        <div class="mobile-form-row">
          <span class="form-label">地点</span>
          <div class="mobile-location-input" @click="showRoomSelectModal = true">
            <span v-if="selectedRoomName" class="location-value">{{ selectedRoomName }}</span>
            <span v-else class="location-placeholder">请选择会议地点</span>
            <a-button v-if="selectedRoomName" type="text" size="small" @click.stop="clearRoomSelection">
              <template #icon><IconClose /></template>
            </a-button>
          </div>
        </div>
        <div class="form-divider"></div>
        <!-- 会议室选择弹窗（移动端样式对齐预约会议） -->
        <a-modal
          v-model:visible="showRoomSelectModal"
          title="选择会议室"
          :footer="false"
          :width="isMobile ? '100vw' : 400"
          :wrap-class-name="isMobile ? 'mobile-modal-wrap' : ''"
          :mask-closable="true"
          @open="fetchFactories"
        >
          <div v-if="isMobile" class="location-selectors">
            <a-form-item label="厂区" class="location-item">
              <a-select
                :key="factoryList.length"
                v-model="selectedFactoryId"
                placeholder="厂区"
                class="location-select"
                @change="onFactoryChange"
              >
                <a-option
                  v-for="factory in factoryList"
                  :key="factory.id"
                  :value="factory.id.toString()"
                >
                  {{ factory.name }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="办公楼" class="location-item">
              <a-select
                v-model="selectedBuildingId"
                placeholder="请选择办公楼"
                @change="onBuildingChange"
              >
                <a-option
                  v-for="building in buildingList"
                  :key="building.id"
                  :value="building.id"
                >
                  {{ building.name }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="楼层" class="location-item">
              <a-select
                v-model="selectedFloor"
                placeholder="请选择楼层"
                :disabled="!selectedBuildingId"
                @change="fetchMeetingRooms"
              >
                <a-option
                  v-for="floor in floorList"
                  :key="floor"
                  :value="floor"
                >
                  {{ floor }}
                </a-option>
              </a-select>
            </a-form-item>
          </div>
          <div class="meeting-rooms-list">
            <div class="section-title">会议室</div>
            <div class="rooms-grid mobile-rooms-grid" style="max-height: 50vh; overflow-y: auto; padding-right: 8px; grid-template-columns: 1fr; gap: 8px;">
              <div
                v-for="room in meetingRoomList"
                :key="room.id"
                class="room-card mobile-room-card"
                :class="{ selected: tempSelectedRoomId === room.id }"
                style="display: flex; align-items: center; padding: 8px; border: 1px solid #e5e6eb; border-radius: 8px; cursor: pointer; background: #fff; transition: border 0.2s, box-shadow 0.2s;"
                @click="selectRoom(room)"
              >
                <div class="room-image" style="width: 50px; height: 50px; margin-right: 12px;">
                  <img :src="room.imageUrl" alt="会议室图片" style="width: 100%; height: 100%; object-fit: cover; border-radius: 4px;" />
                </div>
                <div class="room-info" style="flex: 1; min-width: 0;">
                  <div class="room-name" style="font-size: 14px; font-weight: 500; color: #1d2129; margin-bottom: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ room.name }}</div>
                  <div class="room-capacity" style="color: #86909c; font-size: 12px;">{{ room.floor }}层 · 可容纳{{ room.capacity }}人</div>
                </div>
              </div>
            </div>
            <div class="selector-footer">
              <a-button type="primary" style="width: 100%;" @click="() => selectRoom(meetingRoomList.find(r => r.id === tempSelectedRoomId))">确定</a-button>
            </div>
          </div>
        </a-modal>

        <!-- 重复设置 -->
        <div v-if="isEditMode ? formData.isRecurring : true" class="mobile-form-row">
          <span class="form-label">重复</span>
          <div class="select-wrapper">
            <a-select
              v-model="recurrenceType"
              placeholder="请选择重复类型"
              style="width: 227px;"
              @change="handleRecurrenceTypeChange"
            >
              <a-option value="none">不重复</a-option>
              <a-option value="daily">每天重复</a-option>
              <a-option value="workdays">每个工作日重复</a-option>
              <a-option value="weekly">每周重复</a-option>
              <a-option value="biweekly">每两周重复</a-option>
              <a-option value="monthly">每月重复</a-option>
              <a-option value="custom">自定义...</a-option>
              <a-option v-if="recurrenceType === 'custom-rule'" value="custom-rule">{{ customRuleDescription }}</a-option>
            </a-select>
          </div>
        </div>
        <div v-if="isEditMode ? formData.isRecurring && recurrenceType !== 'none' && recurrenceType !== 'custom' && recurrenceType !== null : recurrenceType !== 'none' && recurrenceType !== 'custom' && recurrenceType !== null" class="form-divider"></div>
        <!-- 结束日期选择器 -->
        <div v-if="isEditMode ? formData.isRecurring && recurrenceType !== 'none' && recurrenceType !== 'custom' && recurrenceType !== null : recurrenceType !== 'none' && recurrenceType !== 'custom' && recurrenceType !== null" class="mobile-form-row">
          <span class="form-label">结束于</span>
          <div class="select-wrapper">
            <a-date-picker
              v-model="cycleParams.endDate"
              format="YYYY-MM-DD"
              placeholder="选择结束日期"
              style="width: 100%;"
            />
          </div>
        </div>
        <div v-if="isEditMode ? formData.isRecurring && recurrenceType !== 'none' && recurrenceType !== 'custom' && recurrenceType !== null : recurrenceType !== 'none' && recurrenceType !== 'custom' && recurrenceType !== null" class="form-divider"></div>

        <!-- 会议设置 -->
        <div class="mobile-form-row">
          <span class="form-label">设置</span>
          <div class="setting-wrapper">
            <a-button type="outline" style="width: 100%;" @click="showMobileSettingsModal = true">
              会议设置
            </a-button>
          </div>
        </div>

        <!-- 按钮组 -->
        <div class="mobile-form-footer">
          <div class="mobile-bottom-buttons">
            <a-button class="mobile-cancel-btn" @click="closeMobileEditPage">取消</a-button>
            <a-button type="primary" class="mobile-confirm-btn" :loading="editLoading" :disabled="editLoading" @click="onEditMeetingSubmit">保存</a-button>
          </div>
        </div>
      </a-form>
    </div>
  </a-modal>

  <!-- 时长选择弹窗 -->
  <a-modal
    v-if="isMobile"
    v-model:visible="showDurationModal"
    :width="isMobile ? '90vw' : 400"
    title="选择时长"
    :footer="false"
    :mask-closable="true"
  >
    <div class="duration-options">
      <div
        v-for="option in durationOptions"
        :key="option.value"
        class="duration-option"
        :class="{ selected: formData.durationType === option.value }"
        @click="selectDuration(option.value)"
      >
        {{ option.label }}
      </div>
    </div>
  </a-modal>

  <!-- 会议设置弹窗 -->
  <a-modal
    v-if="isMobile"
    v-model:visible="showMobileSettingsModal"
    title="会议设置"
    :width="isMobile ? '90vw' : 520"
    :mask-closable="true"
    :footer="true"
    @cancel="showMobileSettingsModal = false"
    @ok="confirmSettings"
  >
    <div class="mobile-setting-section">
      <!-- 会议配置 -->
      <div class="mobile-setting-row" style="margin-bottom: 16px;">
        <span class="setting-label">媒体类型</span>
        <a-select
          v-model="formData.mediaTypes"
          placeholder="请选择媒体类型"
          allow-clear
          style="width: 100%;"
        >
          <a-option value="Voice">音频</a-option>
          <a-option value="HDVideo">视频</a-option>
        </a-select>
      </div>
      <div class="mobile-setting-row" style="margin-bottom: 16px;">
        <a-checkbox
          v-model="formData.confConfigInfo.isGuestFreePwd"
          @change="handleGuestPwdChange"
        >
          开启来宾密码
        </a-checkbox>
        <a-input
          v-if="formData.confConfigInfo.isGuestFreePwd"
          v-model="formData.confConfigInfo.guestPwd"
          placeholder="请输入来宾密码"
          style="margin-top: 8px;"
        />
      </div>
      <div class="mobile-setting-row" style="margin-bottom: 16px;">
        <span class="setting-label">入会范围</span>
        <a-select
          v-model="formData.confConfigInfo.callInRestriction"
          placeholder="请选择入会限制"
          style="width: 100%;"
        >
          <a-option :value="0">无限制</a-option>
          <a-option :value="2">企业内部用户</a-option>
          <a-option :value="3">被邀请用户</a-option>
        </a-select>
      </div>
      <div class="mobile-setting-row">
        <a-checkbox v-model="formData.confConfigInfo.enableWaitingRoom">
          开启等候室
        </a-checkbox>
      </div>
    </div>
  </a-modal>

  <!-- 参会人选择弹窗 -->
  <a-modal
    v-model:visible="showMobileUserSelector"
    :width="isMobile ? '90vw' : 600"
    title="选择参会人"
    :footer="false"
    :wrap-class-name="isMobile ? 'mobile-user-selector-modal-wrap' : ''"
    :mask-closable="true"
    @cancel="closeMobileUserSelector"
  >
    <div class="user-selector-content">
      <a-input-search
        v-model="modalSearchKeyword"
        placeholder="搜索参会人"
        allow-clear
        style="margin-bottom: 16px;"
        @search="handleModalSearch"
      />
      <div v-if="modalSearchResults.length > 0" class="modal-search-results">
        <div
          v-for="user in modalSearchResults"
          :key="user.userId"
          class="search-result-item"
          @click="toggleTempUser(user)"
        >
          <a-checkbox :model-value="tempSelectedUsers.some(u => u.userid === user.userId)" />
          <img :src="user.avatar || 'https://via.placeholder.com/30'" class="user-option-avatar" />
          <span>{{ user.username }}</span>
        </div>
      </div>
      <div v-if="userTreeData.length === 0" style="text-align: center; padding: 20px; color: #999;">
        正在加载组织架构...
      </div>
      <a-tree
        v-else
        v-model:checked-keys="tempCheckedUserIds"
        checkable
        :data="userTreeData"
        class="invite-tree"
        style="max-height: 40vh; overflow-y: auto;"
        @check="handleTreeCheck"
      />
    </div>

    <!-- 已选择用户显示区域 -->
    <div v-if="tempSelectedUsers.length > 0" class="selected-users-preview">
      <div class="selected-title">已选择 {{ tempSelectedUsers.length }} 人（点击头像可取消选择）</div>
      <div class="selected-users-avatars">
        <div
          v-for="user in tempSelectedUsers"
          :key="user.userid"
          class="selected-avatar-item clickable"
          @click="removeTempUserById(user.userid)"
        >
          <div class="avatar-wrapper">
            <img :src="user.avatar || 'https://via.placeholder.com/30'" />
            <div class="remove-overlay">
              <IconClose class="remove-icon" />
            </div>
          </div>
          <span class="user-name">{{ user.name }}</span>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="user-selector-footer">
      <a-space style="width: 100%; justify-content: flex-end;" size="medium">
        <a-button @click="closeMobileUserSelector">取消</a-button>
        <a-button type="primary" @click="confirmMobileUserSelector">
          确定{{ tempSelectedUsers.length > 0 ? `(${tempSelectedUsers.length})` : '' }}
        </a-button>
      </a-space>
    </div>
  </a-modal>

  <!-- 开始时间底部弹窗 -->
  <div v-if="showStartTimePicker && isMobile" class="mobile-bottom-picker-mask">
    <div class="mobile-bottom-picker-new" @click.stop>
      <div class="picker-header-bar">
        <div class="picker-tabs-bar">
          <div class="picker-tab-bar" :class="[activePickerTab === 'date' ? 'active' : '']" @click="activePickerTab = 'date'">{{ tempStartDateLabel }}</div>
          <div class="picker-tab-bar" :class="[activePickerTab === 'time' ? 'active' : '']" @click="activePickerTab = 'time'">{{ tempStartTimeLabel }}</div>
        </div>
        <span class="picker-confirm-bar" @click="confirmStartTime">确定</span>
      </div>
      <div class="picker-content-bar">
        <!-- 日历选择 -->
        <div v-if="activePickerTab === 'date'" class="calendar-bar">
          <div class="calendar-bar-header">
            <span class="calendar-month-btn" style="cursor:pointer;margin-right:12px;" @click="prevMonth">&lt;</span>
            <span>{{ dateYear }}年{{ dateMonth }}月</span>
            <span class="calendar-month-btn" style="cursor:pointer;margin-left:12px;" @click="nextMonth">&gt;</span>
          </div>
          <div class="calendar-bar-week">
            <span v-for="w in ['日', '一', '二', '三', '四', '五', '六']" :key="w">{{ w }}</span>
          </div>
          <div class="calendar-bar-days">
            <span v-for="(d, idx) in calendarDays" :key="idx"
              class="calendar-day"
              :class="[
                d.isCurrent ? 'current' : '',
                d.isDisabled ? 'disabled' : '',
                d.isSelected ? 'selected' : '',
                d.day === null || d.day === '' ? 'empty' : '',
              ]"
              @click="d.day && !d.isDisabled && selectCalendarDay(d)"
            >{{ d.day }}</span>
          </div>
        </div>
        <!-- 时间滚轮 -->
        <div v-if="activePickerTab === 'time'" class="time-scroll-bar">
          <div class="time-scroll-col">
            <ul ref="hourListRef" class="time-scroll-list">
              <li v-for="h in hourList" :key="h" class="time-scroll-item" :class="[h === timeHour ? 'selected' : '', isHourDisabled(h, true) ? 'disabled' : '']" @click="!isHourDisabled(h, true) && selectHour(h)">{{ h.toString().padStart(2, '0') }}</li>
            </ul>
          </div>
          <div class="time-scroll-col">
            <ul ref="minuteListRef" class="time-scroll-list">
              <li v-for="m in minuteList" :key="m" class="time-scroll-item" :class="[m === timeMinute ? 'selected' : '', isMinuteDisabled(timeHour, m, true) ? 'disabled' : '']" @click="!isMinuteDisabled(timeHour, m, true) && selectMinute(m)">{{ m.toString().padStart(2, '0') }}</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 结束时间底部弹窗 -->
  <div v-if="showEndTimePicker && isMobile" class="mobile-bottom-picker-mask">
    <div class="mobile-bottom-picker-new" @click.stop>
      <div class="picker-header-bar">
        <div class="picker-tabs-bar">
          <div class="picker-tab-bar" :class="[activeEndPickerTab === 'date' ? 'active' : '']" @click="activeEndPickerTab = 'date'">{{ tempEndDateLabel }}</div>
          <div class="picker-tab-bar" :class="[activeEndPickerTab === 'time' ? 'active' : '']" @click="activeEndPickerTab = 'time'">{{ tempEndTimeLabel }}</div>
        </div>
        <span class="picker-confirm-bar" @click="confirmEndTime">确定</span>
      </div>
      <div class="picker-content-bar">
        <!-- 日历选择 -->
        <div v-if="activeEndPickerTab === 'date'" class="calendar-bar">
          <div class="calendar-bar-header">
            <span>{{ endDateYear }}年{{ endDateMonth }}月</span>
          </div>
          <div class="calendar-bar-week">
            <span v-for="w in ['日', '一', '二', '三', '四', '五', '六']" :key="w">{{ w }}</span>
          </div>
          <div class="calendar-bar-days">
            <span v-for="(d, idx) in endCalendarDays" :key="idx"
              class="calendar-day"
              :class="[
                d.isCurrent ? 'current' : '',
                d.isDisabled ? 'disabled' : '',
                d.isSelected ? 'selected' : '',
                d.day === null || d.day === '' ? 'empty' : '',
              ]"
              @click="d.day && !d.isDisabled && selectEndCalendarDay(d)"
            >{{ d.day }}</span>
          </div>
        </div>
        <!-- 时间滚轮 -->
        <div v-if="activeEndPickerTab === 'time'" class="time-scroll-bar">
          <div class="time-scroll-col">
            <ul ref="hourListRef" class="time-scroll-list">
              <li v-for="h in hourList" :key="h" class="time-scroll-item" :class="[h === endTimeHour ? 'selected' : '', isHourDisabled(h, false) ? 'disabled' : '']" @click="!isHourDisabled(h, false) && selectEndHour(h)">{{ h.toString().padStart(2, '0') }}</li>
            </ul>
          </div>
          <div class="time-scroll-col">
            <ul ref="minuteListRef" class="time-scroll-list">
              <li v-for="m in minuteList" :key="m" class="time-scroll-item" :class="[m === endTimeMinute ? 'selected' : '', isMinuteDisabled(endTimeHour, m, false) ? 'disabled' : '']" @click="!isMinuteDisabled(endTimeHour, m, false) && selectEndMinute(m)">{{ m.toString().padStart(2, '0') }}</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 自定义周期设置弹窗（手机端） -->
  <a-modal
    v-if="isMobile"
    v-model:visible="showCustomRecurrenceModal"
    title="自定义重复设置"
    :footer="false"
    :closable="true"
    width="90%"
    style="max-width: 400px;"
  >
    <div class="custom-recurrence-modal-content">
      <a-form layout="vertical">
        <a-form-item label="循环类型">
          <a-select v-model="cycleParams.cycle" style="width: 100%;">
            <a-option value="Day">每天</a-option>
            <a-option value="Week">每周</a-option>
            <a-option value="Month">每月</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="间隔周期">
          <a-input-number v-model="cycleParams.interval" :min="1" style="width: 100%;" placeholder="请输入间隔数" />
        </a-form-item>
        <a-form-item v-if="cycleParams.cycle === 'Week'" label="选择周几">
          <a-checkbox-group v-model="cycleParams.point">
            <a-checkbox :value="0">周日</a-checkbox>
            <a-checkbox :value="1">周一</a-checkbox>
            <a-checkbox :value="2">周二</a-checkbox>
            <a-checkbox :value="3">周三</a-checkbox>
            <a-checkbox :value="4">周四</a-checkbox>
            <a-checkbox :value="5">周五</a-checkbox>
            <a-checkbox :value="6">周六</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item v-if="cycleParams.cycle === 'Month'" label="选择日期">
          <a-checkbox-group v-model="cycleParams.point">
            <a-checkbox v-for="d in 31" :key="d" :value="d">{{ d }}日</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="结束日期">
          <a-date-picker v-model="cycleParams.endDate" format="YYYY-MM-DD" style="width: 100%;" placeholder="选择结束日期" />
        </a-form-item>
      </a-form>
      <div style="margin-top: 24px; text-align: right;">
        <a-button style="margin-right: 12px;" @click="showCustomRecurrenceModal = false">取消</a-button>
        <a-button type="primary" @click="onCustomRecurrenceConfirm">确定</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import { debounce } from 'lodash-es'
import { IconCalendar, IconClose, IconDoubleRight } from '@arco-design/web-vue/es/icon'
import { escMeeting, getAvailableFloor, getAvailableRooms, getBuildingList, getFactoryList, getMeetInfo, getRoom, getUserTree, searchUsersAndDevices, updateMeeting } from '@/apis/startApp/meeting'
import { listMeetingRoom } from '@/apis/meet/meetingRoom'
import { useUserStore } from '@/stores'

// 定义返回类型，避免类型错误
interface MeetingParticipant {
  userid: string
  realname: string
  avatar?: string
  role?: number
}

interface MeetingInfo {
  id: number
  conferenceId: string
  meetingRoomId?: number
  mediaType?: number
  meetingRoomName?: string
  subject: string
  size?: number
  startTime: string
  endTime: string
  conferenceState: number
  passwordChair?: string
  passwordGeneral?: string
  createUser: string
  createUserName?: string
  realname?: string
  userInMeeting?: number
  meetType: number
  circleType?: number
  cycleEndDate?: string
  cycle?: string
  interval?: number
  point?: number[]
  location?: string
  conferenceInfo?: string
  callInRestriction?: number
  enableWaitingRoom?: boolean
  autoMute?: number
  timeZone?: string
  createTime?: string
  subInfo?: string
  subCount?: number
  updateTime?: string
  participantList?: string[]
  participants: MeetingParticipant[]
}

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
// 优先从query获取userId，保证接口参数完整
const userId = route.query.userId?.toString() || userStore.userInfo?.id || ''

const loading = ref(true)
const meetingInfo = ref<MeetingInfo | null>(null)

// 判断当前用户是否是会议创建者
const isCreator = computed(() => {
  if (!meetingInfo.value || !userId) return false
  return meetingInfo.value.createUser === userId
})

// 判断会议是否可编辑
const canEditMeeting = computed(() => {
  // 会议状态为0（未开始）才可编辑
  return meetingInfo.value && meetingInfo.value.conferenceState === 0
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return dayjs(date).format('YYYY-MM-DD')
}

// 获取周期会议信息
const getCycleInfo = () => {
  if (!meetingInfo.value) return ''

  const cycleType = meetingInfo.value.cycle
  const interval = meetingInfo.value.interval || 1
  const points = meetingInfo.value.point || []

  if (cycleType === 'Day') {
    return `每${interval === 1 ? '' : interval}天重复`
  } else if (cycleType === 'Week') {
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const days = points.map((p) => weekDays[p]).join('、')
    return `每${interval === 1 ? '' : interval}周的${days}重复`
  } else if (cycleType === 'Month') {
    const days = points.map((p) => `${p}日`).join('、')
    return `每${interval === 1 ? '' : interval}月的${days}重复`
  }

  return ''
}

// 页面加载时获取会议详情
onMounted(async () => {
  const conferenceId = route.params.meetingId as string
  if (!conferenceId) {
    Message.error('会议ID不存在')
    goBack()
    return
  }

  try {
    loading.value = true
    const response = await getMeetInfo(conferenceId, userId)
    console.log('会议详情接口返回:', response)
    if ((String(response.code) === '0' || response.success) && response.data) {
      meetingInfo.value = response.data
    } else {
      Message.error('获取会议详情失败')
    }
  } catch (error) {
    console.error('获取会议详情catch异常:', error)
    Message.error('获取会议详情失败')
  } finally {
    loading.value = false
  }
})

// 会议状态文本
const getConferenceState = (state: number) => {
  const stateMap: Record<number, string> = {
    0: '未开始',
    1: '进行中',
    2: '已结束',
    3: '已取消'
  }
  return stateMap[state] || '未知状态'
}

// 格式化时间
const getTime = (time: string) => {
  if (!time) return ''
  const formatTime = dayjs(time).format('YYYY-MM-DD HH:mm')
  return formatTime
}

// 获取参会人字符串
const getParticipantStr = (participants: MeetingParticipant[]) => {
  if (!participants || !participants.length) return '无'
  return participants.map((p) => p.realname).join('、')
}

// 进入会议
const joinMeeting = () => {
  if (meetingInfo.value && meetingInfo.value.conferenceId) {
    window.open(`https://meeting.fortunesemic.com/joinUrl?conferenceId=${meetingInfo.value.conferenceId}`)
  } else {
    Message.error('无法进入会议，会议ID不存在')
  }
}

// 复制会议链接
const copyLink = () => {
  if (!meetingInfo.value || !meetingInfo.value.conferenceId) {
    Message.error('会议链接不存在')
    return
  }
  const url = `https://meeting.fortunesemic.com/joinUrl?conferenceId=${meetingInfo.value.conferenceId}`
  navigator.clipboard.writeText(url)
    .then(() => {
      Message.success('会议链接已复制到剪贴板')
    })
    .catch(() => {
      Message.error('复制失败，请手动复制')
    })
}

// 编辑会议将在后面定义

// 显示取消会议确认框（与PC端一致，使用escMeeting接口）
const showCancelConfirm = () => {
  if (!meetingInfo.value || !meetingInfo.value.conferenceId) return

  Modal.confirm({
    title: '取消会议',
    content: '确认要取消此会议吗？',
    onOk: async () => {
      try {
        const response = await escMeeting(meetingInfo.value!.conferenceId)
        if (response.data.code === '0' && response.data.success) {
          Message.success('会议已取消')
          goBack()
        } else {
          Message.error(response.data.msg || '取消会议失败')
        }
      } catch (err) {
        console.error('取消会议失败', err)
        Message.error('取消会议失败')
      }
    }
  })
}

// 判断是否为移动端
const isMobile = ref(false)
if (typeof window !== 'undefined') {
  isMobile.value = window.innerWidth <= 768
}

// 编辑会议
const editMeeting = () => {
  if (!canEditMeeting.value) {
    Message.warning('已开始或已结束的会议不可编辑')
    return
  }
  if (meetingInfo.value && meetingInfo.value.conferenceId) {
    if (isMobile.value) {
      // 移动端直接在当前页面弹出编辑弹窗
      loadMeetingForEdit(meetingInfo.value.conferenceId)
    } else {
      // PC端跳转到编辑页面
      router.push({
        path: '/meet/edit-meet',
        query: {
          conferenceId: meetingInfo.value.conferenceId
        }
      })
    }
  }
}

// 加载会议信息进行编辑
const loadMeetingForEdit = async (conferenceId: string) => {
  try {
    const response = await getMeetInfo(conferenceId, userId)
    if (String(response.code) === '0' && response.data) {
      const meeting = response.data

      // 填充表单数据
      formData.value.subject = meeting.subject || ''
      formData.value.startTime = meeting.startTime || ''
      formData.value.startDate = meeting.startTime ? dayjs(meeting.startTime).format('YYYY-MM-DD') : ''
      formData.value.startTimeOfDay = meeting.startTime ? dayjs(meeting.startTime).format('HH:mm') : ''
      formData.value.length = meeting.length || 60
      formData.value.durationType = String(meeting.length || 60)
      formData.value.endDate = meeting.endTime ? dayjs(meeting.endTime).format('YYYY-MM-DD') : ''
      formData.value.endTimeOfDay = meeting.endTime ? dayjs(meeting.endTime).format('HH:mm') : ''
      formData.value.meetType = meeting.meetType || 1
      formData.value.mediaTypes = meeting.mediaTypes || 'HDVideo'
      formData.value.meetRoomId = meeting.meetRoomId
      formData.value._conferenceId = conferenceId

      // 填充参会人
      if (meeting.participants && Array.isArray(meeting.participants)) {
        selectedUsers.value = meeting.participants
          .filter((p) => typeof p.type === 'undefined' || p.type !== 0)
          .map((p) => ({
            userid: p.userId || p.userid || '',
            name: p.realname || p.name || '',
            avatar: p.avatar || '',
            type: typeof (p as any).type !== 'undefined' ? (p as any).type : 1 // 补充type字段，默认1
          }))
      }

      // 填充地点信息
      if (meeting.location) {
        selectedRoomName.value = meeting.location
      } else if (meeting.meetRoomId && meetingRoomList.value.length) {
        const room = meetingRoomList.value.find((r) => r.id == meeting.meetRoomId)
        selectedRoomName.value = room ? room.name : (meeting.location || '')
      } else {
        selectedRoomName.value = ''
      }
      formData.value.meetRoomId = meeting.meetRoomId

      // 填充会议配置信息（与PC端保持一致）
      formData.value.confConfigInfo = {
        isGuestFreePwd: !!(meeting.passwordGeneral && meeting.passwordGeneral !== ''),
        guestPwd: meeting.passwordGeneral || '',
        callInRestriction: typeof meeting.callInRestriction !== 'undefined' ? meeting.callInRestriction : 0,
        enableWaitingRoom: !!meeting.enableWaitingRoom,
        enableSignOut: Number(meeting.enableSignOut) || 0,
        signInBeforeMinutes: meeting.signInBeforeMinutes || '',
        signOutMinutesAfterSignIn: meeting.signOutMinutesAfterSignIn || '',
        signOutAfterEndMinutes: meeting.signOutAfterEndMinutes || ''
      }

      // 兼容媒体类型字段
      if (typeof meeting.mediaType !== 'undefined') {
        formData.value.mediaTypes = meeting.mediaType === 1 ? 'HDVideo' : 'Voice'
      } else {
        formData.value.mediaTypes = meeting.mediaTypes || 'HDVideo'
      }

      // 处理周期会议信息（统一所有周期类型的参数回填和表单同步）
      if (meeting.cycle && meeting.interval && Array.isArray(meeting.point)) {
        // 统一周期参数结构
        const cycleParamObj = {
          startDate: meeting.cycleStartDate || meeting.startDate || meeting.startTime?.split(' ')[0] || '',
          endDate: meeting.cycleEndDate || meeting.endDate || '',
          cycle: meeting.cycle,
          interval: meeting.interval,
          point: Array.isArray(meeting.point) ? meeting.point : [],
          weekDay: Array.isArray(meeting.point) ? meeting.point : []
        }
        cycleParams.value = { ...cycleParamObj }
        formData.value.cycleParams = { ...cycleParamObj }
        // 设置recurrenceType和自定义描述
        if (meeting.cycle === 'Month') {
          if (meeting.point && meeting.point.length > 1) {
            recurrenceType.value = 'custom-rule'
            customRuleDescription.value = `每${meeting.interval > 1 ? meeting.interval : ''}月的${meeting.point.map((p) => `${p}日`).join('、')}重复`
          } else {
            recurrenceType.value = 'monthly'
            customRuleDescription.value = ''
          }
        } else if (meeting.cycle === 'Day') {
          recurrenceType.value = 'daily'
        } else if (meeting.cycle === 'Week') {
          const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
          if (meeting.point && meeting.point.length > 1) {
            recurrenceType.value = 'custom-rule'
            customRuleDescription.value = `每${meeting.interval > 1 ? meeting.interval : ''}周的${meeting.point.map((p) => weekDays[p]).join('、')}重复`
          } else {
            recurrenceType.value = 'weekly'
            customRuleDescription.value = ''
          }
        } else {
          recurrenceType.value = 'custom'
        }
        formData.value.isRecurring = true
      } else {
        recurrenceType.value = 'none'
        cycleParams.value = {
          startDate: '',
          endDate: '',
          cycle: '',
          interval: 1,
          weekDay: [],
          point: []
        }
        formData.value.isRecurring = false
      }

      // 填充会议室名称（优先接口获取）
      const meetRoomId = meeting.meetRoomId || meeting.meetingRoomId
      console.log('编辑会议回填 meetRoomId:', meetRoomId)
      let roomDetail = null // 修正：提前声明
      if (meetRoomId) {
        try {
          roomDetail = await getRoom(meetRoomId)
          const roomData = (roomDetail as any).data
          console.log('getRoom返回:', roomDetail)
          if (roomData && roomData.name) {
            selectedRoomName.value = roomData.name
          } else {
            selectedRoomName.value = meeting.meetingRoomName || meeting.location || ''
          }
        } catch (e) {
          selectedRoomName.value = meeting.meetingRoomName || meeting.location || ''
        }
        formData.value.meetRoomId = meetRoomId
        tempSelectedRoomId.value = meetRoomId
        if ((roomDetail as any)?.data) {
          const roomData = (roomDetail as any).data
          selectedFactoryId.value = roomData.factoryId || ''
          selectedBuildingId.value = roomData.buildingId || ''
          selectedFloor.value = roomData.floor || ''
        }
        formData.value.meetType = 0 // 只要有会议室id，强制线下会议
      } else {
        selectedRoomName.value = meeting.meetingRoomName || meeting.location || ''
        formData.value.meetRoomId = ''
        tempSelectedRoomId.value = ''
      }

      isEditMode.value = true
      editConferenceId.value = conferenceId
      showMobileEditPage.value = true
      // 回填 selectedDate，保证日历弹窗默认选中会议开始日期
      selectedDate.value = meeting.startTime ? dayjs(meeting.startTime) : dayjs()
    }
  } catch (error) {
    console.error('加载会议信息失败:', error)
    Message.error('获取会议详情失败')
  }
}

// 关闭编辑弹窗
const closeMobileEditPage = () => {
  showMobileEditPage.value = false
  isEditMode.value = false
  editConferenceId.value = ''
  resetEditFormData()
}

// 重置编辑表单数据
const resetEditFormData = () => {
  formData.value = {
    subject: '',
    startTime: '',
    startDate: '',
    startTimeOfDay: '',
    length: 60,
    durationType: '60',
    isCustomEndTime: false,
    endDate: '',
    endTimeOfDay: '',
    mediaTypes: 'HDVideo',
    meetRoomId: '',
    meetType: 1,
    remindTime: '0',
    confConfigInfo: {
      isGuestFreePwd: false,
      callInRestriction: 0,
      guestPwd: '',
      enableWaitingRoom: false,
      enableSignOut: 0,
      signInBeforeMinutes: '',
      signOutMinutesAfterSignIn: '',
      signOutAfterEndMinutes: ''
    },
    cycleParams: {
      startDate: '',
      endDate: '',
      cycle: '',
      interval: 1,
      weekDay: [] as number[],
      point: [] as number[]
    },
    isOnline: true,
    isRecurring: false,
    _conferenceId: '',
    offlineParam: ''
  }
  selectedUsers.value = []
  selectedRoomName.value = ''
  recurrenceType.value = 'none'
}

// 提交编辑会议
const onEditMeetingSubmit = async () => {
  // 新增：根据地点自动设置会议类型
  if (selectedRoomName.value && selectedRoomName.value.trim() !== '') {
    formData.value.meetType = 0
  } else {
    formData.value.meetType = 1
  }
  if (editLoading.value) return
  editLoading.value = true
  try {
    // 验证必填字段
    if (!formData.value.subject.trim()) {
      Message.error('请输入会议主题')
      return
    }
    if (!formData.value.startDate || !formData.value.startTimeOfDay) {
      Message.error('请选择开始时间')
      return
    }

    // 构建参数（与预约会议一致）
    const requestData = {
      userId, // 取自 URL
      subject: formData.value.subject,
      startTime: `${formData.value.startDate} ${formData.value.startTimeOfDay}:00`,
      length: formData.value.length || Number(formData.value.durationType),
      mediaTypes: formData.value.mediaTypes || 'HDVideo',
      meetRoomId: formData.value.meetRoomId,
      meetType: formData.value.meetType,
      remindTime: formData.value.remindTime,
      enableSignOut: formData.value.confConfigInfo?.enableSignOut || 0,
      signInBeforeMinutes: formData.value.confConfigInfo?.signInBeforeMinutes || '',
      signOutMinutesAfterSignIn: formData.value.confConfigInfo?.signOutMinutesAfterSignIn || '',
      signOutAfterEndMinutes: formData.value.confConfigInfo?.signOutAfterEndMinutes || '',
      confConfigInfo: {
        isGuestFreePwd: !formData.value.confConfigInfo.isGuestFreePwd,
        callInRestriction: formData.value.confConfigInfo?.callInRestriction || 0,
        guestPwd: formData.value.confConfigInfo?.guestPwd || '',
        enableWaitingRoom: formData.value.confConfigInfo?.enableWaitingRoom || false
      },
      // 周期会议参数
      cycleParams: formData.value.isRecurring ? { ...formData.value.cycleParams } : undefined,
      attendees: selectedUsers.value.map((user) => {
        const attendee: any = {
          accountId: user.userid,
          appId: '9dbd6b334e744eada42b45b3bf6b8402'
        }
        if (user.type === 0) {
          attendee.type = 1
        }
        return attendee
      }),
      conferenceId: editConferenceId.value
    }

    const response = await updateMeeting(requestData)
    if (String(response.code) === '0' || response.success) {
      Message.success('会议已更新')
      closeMobileEditPage()
      // 刷新会议详情
      window.location.reload()
    } else {
      Message.error(response.msg || '更新会议失败')
    }
  } finally {
    editLoading.value = false
  }
}

// 获取时长标签
const getDurationLabel = (value: string) => {
  const option = durationOptions.find((opt) => opt.value === value)
  return option ? option.label : `${value}分钟`
}

// 选择时长
const selectDuration = (value: string) => {
  formData.value.durationType = value
  formData.value.length = Number(value)
  showDurationModal.value = false
}

// 获取开始日期显示
const getStartDateDisplay = () => {
  if (!formData.value.startDate) return '选择日期'
  const date = dayjs(formData.value.startDate)
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  return `${date.format('M月D日')} 周${weekDays[date.day()]} `
}

// 获取开始时间显示
const getStartTimeDisplay = () => {
  return formData.value.startTimeOfDay || '选择时间'
}

// 获取结束日期显示
const getEndDateDisplay = () => {
  if (!formData.value.endDate) return '选择日期'
  const date = dayjs(formData.value.endDate)
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  return `${date.format('M月D日')} 周${weekDays[date.day()]} `
}

// 获取结束时间显示
const getEndTimeDisplay = () => {
  return formData.value.endTimeOfDay || '选择时间'
}

// 处理重复类型变化
const handleRecurrenceTypeChange = (value: string | number | boolean | Record<string, any> | (string | number | boolean | Record<string, any>)[]) => {
  if (typeof value !== 'string') return
  if (value === 'custom') {
    showCustomRecurrenceModal.value = true
    return
  }
  if (value === 'none') {
    formData.value.isRecurring = false
    cycleParams.value = {
      startDate: '',
      endDate: '',
      cycle: '',
      interval: 1,
      weekDay: [],
      point: []
    }
    return
  }
  formData.value.isRecurring = true
  const startDate = formData.value.startDate || dayjs().format('YYYY-MM-DD')
  const endDate = dayjs(startDate).add(7, 'day').format('YYYY-MM-DD')
  if (value === 'workdays') {
    cycleParams.value = {
      startDate,
      endDate,
      cycle: 'Week',
      interval: 1,
      weekDay: [1, 2, 3, 4, 5],
      point: [1, 2, 3, 4, 5]
    }
  } else if (value === 'weekly') {
    const weekDayNum = dayjs(startDate).day()
    cycleParams.value = {
      startDate,
      endDate,
      cycle: 'Week',
      interval: 1,
      weekDay: [weekDayNum],
      point: [weekDayNum]
    }
  } else if (value === 'biweekly') {
    const weekDayNum = dayjs(startDate).day()
    cycleParams.value = {
      startDate,
      endDate,
      cycle: 'Week',
      interval: 2,
      weekDay: [weekDayNum],
      point: [weekDayNum]
    }
  } else if (value === 'monthly') {
    const dayNum = dayjs(startDate).date()
    cycleParams.value = {
      startDate,
      endDate,
      cycle: 'Month',
      interval: 1,
      weekDay: [],
      point: [dayNum]
    }
  } else if (value === 'daily') {
    cycleParams.value = {
      startDate,
      endDate,
      cycle: 'Day',
      interval: 1,
      weekDay: [],
      point: []
    }
  }
  formData.value.startDate = startDate
}

// TreeNode类型声明
interface TreeNode {
  title: string
  key: string
  value: string
  selectable: boolean
  disabled: boolean
  disableCheckbox: boolean
  isLeaf: boolean
  class: string
  children: TreeNode[]
  avatar: string | null
}

// 数据转换函数
const transformTreeData = (data: any[]): TreeNode[] => {
  return data.map((node) => {
    const isUser = node.type === 'user'
    const isDepartment = node.type === 'department'
    const isCurrentUser = isUser && node.userid === userId

    return {
      title: node.name,
      key: isUser ? node.userid : node.id.toString(),
      value: isUser ? node.userid : node.id.toString(),
      selectable: isUser && !isCurrentUser,
      disabled: isDepartment || isCurrentUser,
      disableCheckbox: isDepartment,
      isLeaf: !node.children?.length,
      class: isDepartment ? 'department-node' : isUser ? 'user-node' : '',
      children: node.children ? transformTreeData(node.children) : [],
      avatar: isUser ? node.avatar : null
    }
  })
}

// 递归查找用户节点
const findUserById = (tree: any[], userid: string): any | null => {
  for (const node of tree) {
    if (node.value === userid) return node
    if (node.children) {
      const found = findUserById(node.children, userid)
      if (found) return found
    }
  }
  return null
}

// 参会人选择相关函数
const openMobileUserSelector = async () => {
  try {
    const rawData = await getUserTree()
    console.log('getUserTree response:', rawData)
    console.log('原始用户树数据:', rawData)

    userTreeData.value = transformTreeData(rawData)
    console.log('转换后的用户树数据:', userTreeData.value)

    tempSelectedUsers.value = [...selectedUsers.value]
    tempCheckedUserIds.value = tempSelectedUsers.value.map((u) => u.userid)
    showMobileUserSelector.value = true
  } catch (error) {
    console.error('获取用户树失败:', error)
    Message.error('获取用户列表失败')
  }
}

const closeMobileUserSelector = () => {
  showMobileUserSelector.value = false
}

const confirmMobileUserSelector = () => {
  selectedUsers.value = [...tempSelectedUsers.value]
  showMobileUserSelector.value = false
}

const toggleTempUser = (user: any) => {
  const idx = tempSelectedUsers.value.findIndex((u) => u.userid === user.userId)
  if (idx > -1) {
    tempSelectedUsers.value.splice(idx, 1)
    tempCheckedUserIds.value = tempCheckedUserIds.value.filter((id) => id !== user.userId)
  } else {
    tempSelectedUsers.value.push({
      userid: user.userId,
      name: user.username,
      avatar: user.avatar || ''
    })
    tempCheckedUserIds.value.push(user.userId)
  }
}

const removeTempUserById = (userid: string) => {
  const idx = tempSelectedUsers.value.findIndex((u) => u.userid === userid)
  if (idx > -1) {
    tempSelectedUsers.value.splice(idx, 1)
    tempCheckedUserIds.value = tempCheckedUserIds.value.filter((id) => id !== userid)
  }
}

// 处理树节点选择
const handleTreeCheck = (checkedKeys: (string | number)[], data: any) => {
  console.log('Tree check event:', checkedKeys, data)
  const stringKeys = checkedKeys.map((key) => String(key))
  tempCheckedUserIds.value = stringKeys

  // 根据选中的keys更新tempSelectedUsers
  tempSelectedUsers.value = stringKeys
    .map((key) => {
      const userNode = findUserById(userTreeData.value, key)
      if (userNode && userNode.class === 'user-node') {
        return {
          userid: key,
          name: userNode.title,
          avatar: userNode.avatar || ''
        }
      }
      return null
    })
    .filter(Boolean) as Array<{ userid: string, name: string, avatar: string }>
}

// 用户搜索
const handleModalSearch = debounce(async (value: string | number | boolean | Record<string, any> | (string | number | boolean | Record<string, any>)[]) => {
  if (typeof value !== 'string') return
  modalSearchKeyword.value = value
  if (!value.trim()) {
    modalSearchResults.value = []
    return
  }

  try {
    // 调用API进行搜索
    const res = await searchUsersAndDevices(value)

    // 过滤只保留用户类型的结果
    modalSearchResults.value = res.filter((item: any) =>
      item.type === 1 || item.type === 'user' || !item.type
    ).map((user: any) => ({
      userId: user.userId || user.userid,
      username: user.username || user.name,
      avatar: user.avatar || '',
      type: 'user'
    }))
  } catch (error) {
    console.error('搜索用户失败:', error)
    Message.error('搜索用户失败')
    modalSearchResults.value = []
  }
}, 300)

// 清除房间选择
const clearRoomSelection = () => {
  selectedRoomName.value = ''
  formData.value.meetRoomId = ''
}

// 会议设置相关函数
const confirmSettings = () => {
  showMobileSettingsModal.value = false
}

const handleGuestPwdChange = (value: boolean | (string | number | boolean)[], ev?: Event) => {
  if (typeof value !== 'boolean') return
  if (!value) {
    formData.value.confConfigInfo.guestPwd = ''
  }
}

// 参会人弹窗控制
const showParticipantsModal = ref(false)
const maxShowParticipants = 4
const participantsList = computed(() => meetingInfo.value?.participants || [])
const extraCount = computed(() => Math.max(0, participantsList.value.length - maxShowParticipants))

// 监听会议详情变化，关闭弹窗
watch(meetingInfo, () => { showParticipantsModal.value = false })

// 子会议管理相关变量
const showSubMeetingModal = ref(false)
const showEditSubModal = ref(false)
const subMeetingList = ref<any[]>([])
const editSubLoading = ref(false)
const currentSubMeetingDetail = ref<MeetingInfo | null>(null)

// 编辑会议相关变量
const showMobileEditPage = ref(false)
const selectedUsers = ref<Array<{ userid: string, name: string, avatar: string, type?: number }>>([])
const selectedRoomName = ref('')
const formData = ref({
  subject: '',
  startTime: '',
  startDate: '',
  startTimeOfDay: '',
  length: 60,
  durationType: '60',
  isCustomEndTime: false,
  endDate: '',
  endTimeOfDay: '',
  mediaTypes: 'HDVideo',
  meetRoomId: '',
  meetType: 1,
  remindTime: '0',
  confConfigInfo: {
    isGuestFreePwd: false,
    callInRestriction: 0,
    guestPwd: '',
    enableWaitingRoom: false,
    enableSignOut: 0,
    signInBeforeMinutes: '',
    signOutMinutesAfterSignIn: '',
    signOutAfterEndMinutes: ''
  },
  cycleParams: {
    startDate: '',
    endDate: '',
    cycle: '',
    interval: 1,
    weekDay: [] as number[],
    point: [] as number[]
  },
  isOnline: true,
  isRecurring: false,
  _conferenceId: '',
  offlineParam: ''
})
const recurrenceType = ref('none')
const cycleParams = ref<{
  startDate: string
  endDate: string
  cycle: string
  interval: number
  weekDay: number[]
  point: number[]
}>({
  startDate: '',
  endDate: '',
  cycle: '',
  interval: 1,
  weekDay: [] as number[],
  point: [] as number[]
})
const isEditMode = ref(false)
const editConferenceId = ref('')
const showStartTimePicker = ref(false)
const showEndTimePicker = ref(false)
const showDurationModal = ref(false)
const activePickerTab = ref('date')
const activeEndPickerTab = ref('date')
const showRoomSelectModal = ref(false)
const showMobileSettingsModal = ref(false)
const showMobileUserSelector = ref(false)
const tempSelectedUsers = ref<Array<{ userid: string, name: string, avatar: string, type?: number }>>([])
const tempCheckedUserIds = ref<string[]>([])
const userTreeData = ref<any[]>([])
const modalSearchResults = ref<any[]>([])
const modalSearchKeyword = ref('')

// 时长选项
const durationOptions = [
  { value: '15', label: '15分钟' },
  { value: '30', label: '30分钟' },
  { value: '45', label: '45分钟' },
  { value: '60', label: '1小时' },
  { value: '90', label: '1小时30分钟' },
  { value: '120', label: '2小时' },
  { value: '150', label: '2小时30分钟' },
  { value: '180', label: '3小时' },
  { value: '240', label: '4小时' },
  { value: '300', label: '5小时' },
  { value: '360', label: '6小时' },
  { value: '420', label: '7小时' },
  { value: '480', label: '8小时' }
]

// 子会议编辑表单
const editSubForm = ref({
  cycleSubConfID: '',
  mediaTypes: '',
  conferenceId: '',
  startTime: '',
  length: 60,
  userId: ''
})

// 打开子会议管理模态框
const openSubMeetingModal = async () => {
  if (!meetingInfo.value?.conferenceId) return

  showSubMeetingModal.value = true

  try {
    const response = await getMeetInfo(meetingInfo.value.conferenceId, userId)
    if (String(response.code) === '0' && response.data) {
      currentSubMeetingDetail.value = response.data
      // 展平所有子会议
      if (response.data.subMeet && Array.isArray(response.data.subMeet)) {
        subMeetingList.value = response.data.subMeet.flatMap((monthGroup: any) => monthGroup.sub || [])
      } else {
        subMeetingList.value = []
      }
    } else {
      subMeetingList.value = []
    }
  } catch (error) {
    console.error('获取子会议失败:', error)
    subMeetingList.value = []
    Message.error('获取子会议失败')
  }
}

// 三点菜单下拉操作
const handleMenuSelect = (value: string | number | boolean | Record<string, any> | (string | number | boolean | Record<string, any>)[]) => {
  if (value === 'edit') {
    if (!canEditMeeting.value) {
      Message.warning('已开始或已结束的会议不可编辑')
      return
    }
    editMeeting()
  }
  if (value === 'cancel') showCancelConfirm()
  if (value === 'editSub') openSubMeetingModal()
}

// 新增：移动端时间格式（优化：今天、x月x日）
const getMobileTime = (start?: string, end?: string) => {
  if (!start || !end) return ''
  const s = dayjs(start)
  const e = dayjs(end)
  const now = dayjs()
  let prefix = ''
  if (s.isSame(now, 'day')) {
    prefix = '今天 '
  }
  // 日期格式 x月x日
  const dateStr = `${s.month() + 1}月${s.date()}日`
  const weekDayMap = ['日', '一', '二', '三', '四', '五', '六']
  return `${prefix}${dateStr} 周${weekDayMap[s.day()]} ${s.format('HH:mm')} - ${e.format('HH:mm')}`
}

// 新增：移动端周期会议结束日期格式
const formatMobileCycleEnd = (date: string) => {
  if (!date) return ''
  const d = dayjs(date)
  return `${d.year()}年${d.month() + 1}月${d.date()}日结束`
}

// 编辑子会议
const editSubMeeting = (sub: any) => {
  // 获取mediaTypes
  let mediaTypes = ''
  if (currentSubMeetingDetail.value) {
    if (currentSubMeetingDetail.value.conferenceInfo) {
      try {
        const info = JSON.parse(currentSubMeetingDetail.value.conferenceInfo)
        const types = (info.mediaTypes || info.mediaType || '').split(',')
        if (types.includes('HDVideo')) {
          mediaTypes = 'HDVideo'
        } else if (types.includes('Video')) {
          mediaTypes = 'Video'
        } else if (types.includes('Voice')) {
          mediaTypes = 'Voice'
        } else {
          mediaTypes = types[0] || 'Voice'
        }
      } catch {}
    }
    if (!mediaTypes && (currentSubMeetingDetail.value as any).mediaType) {
      const types = String((currentSubMeetingDetail.value as any).mediaType).split(',')
      if (types.includes('HDVideo')) {
        mediaTypes = 'HDVideo'
      } else if (types.includes('Video')) {
        mediaTypes = 'Video'
      } else if (types.includes('Voice')) {
        mediaTypes = 'Voice'
      } else {
        mediaTypes = types[0] || 'Voice'
      }
    }
  }

  editSubForm.value = {
    cycleSubConfID: sub.cycleSubConfID,
    mediaTypes,
    conferenceId: currentSubMeetingDetail.value?.conferenceId || '',
    startTime: sub.startTime,
    length: sub.length || 60,
    userId: userId || ''
  }
  showEditSubModal.value = true
}

// 删除子会议
const deleteSubMeeting = async (sub: any) => {
  Modal.confirm({
    title: '删除子会议',
    content: '确认要删除这场子会议吗？',
    onOk: async () => {
      try {
        // 获取mediaTypes（同编辑逻辑）
        let mediaTypes = ''
        if (currentSubMeetingDetail.value) {
          if (currentSubMeetingDetail.value.conferenceInfo) {
            try {
              const info = JSON.parse(currentSubMeetingDetail.value.conferenceInfo)
              const types = (info.mediaTypes || info.mediaType || '').split(',')
              if (types.includes('HDVideo')) {
                mediaTypes = 'HDVideo'
              } else if (types.includes('Video')) {
                mediaTypes = 'Video'
              } else if (types.includes('Voice')) {
                mediaTypes = 'Voice'
              } else {
                mediaTypes = types[0] || 'Voice'
              }
            } catch {}
          }
          if (!mediaTypes && (currentSubMeetingDetail.value as any).mediaType) {
            const types = String((currentSubMeetingDetail.value as any).mediaType).split(',')
            if (types.includes('HDVideo')) {
              mediaTypes = 'HDVideo'
            } else if (types.includes('Video')) {
              mediaTypes = 'Video'
            } else if (types.includes('Voice')) {
              mediaTypes = 'Voice'
            } else {
              mediaTypes = types[0] || 'Voice'
            }
          }
        }

        const params = {
          cycleSubConfID: sub.cycleSubConfID,
          mediaTypes,
          conferenceId: currentSubMeetingDetail.value?.conferenceId,
          userId: userId || ''
        }

        await fetch('https://meeting.fortunesemic.com/api/wecom/cancelSubMeet', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(params)
        })

        Message.success('子会议已删除')
        // 刷新子会议列表
        openSubMeetingModal()
      } catch (error) {
        console.error('删除子会议失败:', error)
        Message.error('删除子会议失败')
      }
    }
  })
}

// 提交编辑子会议
const submitEditSubMeeting = async () => {
  editSubLoading.value = true
  try {
    await fetch('https://meeting.fortunesemic.com/api/wecom/updateSubMeet', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        cycleSubConfID: editSubForm.value.cycleSubConfID,
        mediaTypes: editSubForm.value.mediaTypes,
        conferenceId: editSubForm.value.conferenceId,
        startTime: editSubForm.value.startTime,
        length: editSubForm.value.length,
        userId: editSubForm.value.userId
      })
    })

    Message.success('子会议已更新')
    showEditSubModal.value = false
    // 刷新子会议列表
    openSubMeetingModal()
  } catch (error) {
    console.error('编辑子会议失败:', error)
    Message.error('编辑子会议失败')
  } finally {
    editSubLoading.value = false
  }
}

// 取消编辑子会议
const cancelEditSubMeeting = () => {
  showEditSubModal.value = false
  editSubForm.value = {
    cycleSubConfID: '',
    mediaTypes: '',
    conferenceId: '',
    startTime: '',
    length: 60,
    userId: ''
  }
}

// 格式化子会议时间
const formatSubMeetingTime = (startTime: string, endTime: string) => {
  if (!startTime || !endTime) return ''
  const start = dayjs(startTime)
  const end = dayjs(endTime)

  const now = dayjs()
  let prefix = ''
  if (start.isSame(now, 'day')) {
    prefix = '今天 '
  }

  const dateStr = `${start.month() + 1}月${start.date()}日`
  const weekDayMap = ['日', '一', '二', '三', '四', '五', '六']
  return `${prefix}${dateStr} 周${weekDayMap[start.day()]} ${start.format('HH:mm')} - ${end.format('HH:mm')}`
}

// 开始时间底部弹窗
const confirmStartTime = () => {
  formData.value.startDate = selectedDate.value.format('YYYY-MM-DD')
  cycleParams.value.startDate = formData.value.startDate
  formData.value.startTimeOfDay = `${timeHour.value.toString().padStart(2, '0')}:${timeMinute.value.toString().padStart(2, '0')}`
  // 修复：仅在 point 为空时才自动赋值，避免多选被覆盖
  if (cycleParams.value.cycle === 'Week' && (!cycleParams.value.point || cycleParams.value.point.length === 0)) {
    const weekDayNum = dayjs(formData.value.startDate).day()
    cycleParams.value.point = [weekDayNum]
    cycleParams.value.weekDay = [weekDayNum]
  } else if (cycleParams.value.cycle === 'Month' && (!cycleParams.value.point || cycleParams.value.point.length === 0)) {
    const dayNum = dayjs(formData.value.startDate).date()
    cycleParams.value.point = [dayNum]
  } else if (cycleParams.value.cycle === 'Week' && cycleParams.value.interval === 2 && (!cycleParams.value.point || cycleParams.value.point.length === 0)) {
    const weekDayNum = dayjs(formData.value.startDate).day()
    cycleParams.value.point = [weekDayNum]
    cycleParams.value.weekDay = [weekDayNum]
  } else if (cycleParams.value.cycle === 'Day') {
    cycleParams.value.point = []
  }
  showStartTimePicker.value = false
}

// 结束时间底部弹窗
const confirmEndTime = () => {
  formData.value.endDate = selectedEndDate.value.format('YYYY-MM-DD')
  formData.value.endTimeOfDay = `${endTimeHour.value.toString().padStart(2, '0')}:${endTimeMinute.value.toString().padStart(2, '0')}`
  showEndTimePicker.value = false
}

// 选择日期
const selectCalendarDay = (d: any) => {
  if (d.isDisabled) return
  selectedDate.value = selectedDate.value.date(d.day)
  calendarDays.value = getCalendarDays(selectedDate.value.year(), selectedDate.value.month() + 1, selectedDate.value)
}

// 选择结束日期
const selectEndCalendarDay = (d: any) => {
  if (d.isDisabled) return
  selectedEndDate.value = selectedEndDate.value.date(d.day)
  endCalendarDays.value = getCalendarDays(selectedEndDate.value.year(), selectedEndDate.value.month() + 1, selectedEndDate.value)
}

// 选择时间
const selectHour = (h: number) => {
  timeHour.value = h
  selectedTime.value = selectedTime.value.hour(h)
}

// 选择结束时间
const selectEndHour = (h: number) => {
  endTimeHour.value = h
  selectedEndTime.value = selectedEndTime.value.hour(h)
}

// 选择分钟
const selectMinute = (m: number) => {
  timeMinute.value = m
  selectedTime.value = selectedTime.value.minute(m)
}

// 选择结束分钟
const selectEndMinute = (m: number) => {
  endTimeMinute.value = m
  selectedEndTime.value = selectedEndTime.value.minute(m)
}

// 是否禁用时间
const isHourDisabled = (hour: number, isStart: boolean) => {
  // 仅当天才禁用当前时间之前
  const todayStr = dayjs().format('YYYY-MM-DD')
  const compareDate = isStart ? selectedDate.value.format('YYYY-MM-DD') : selectedEndDate.value.format('YYYY-MM-DD')
  if (compareDate !== todayStr) return false
  const nowHour = dayjs().hour()
  return hour < nowHour
}

// 是否禁用分钟
const isMinuteDisabled = (hour: number, minute: number, isStart: boolean) => {
  // 仅当天才禁用当前时间之前
  const todayStr = dayjs().format('YYYY-MM-DD')
  const compareDate = isStart ? selectedDate.value.format('YYYY-MM-DD') : selectedEndDate.value.format('YYYY-MM-DD')
  if (compareDate !== todayStr) return false
  const nowHour = dayjs().hour()
  const nowMinute = dayjs().minute()
  if (hour < nowHour) return true
  if (hour === nowHour && minute < nowMinute) return true
  return false
}

// 日期选择
const selectedDate = ref(dayjs())
const selectedTime = ref(dayjs())
const selectedEndDate = ref(dayjs())
const selectedEndTime = ref(dayjs())

// 日期选择标签（动态）
const tempStartDateLabel = ref('')
const tempStartTimeLabel = ref('')
const tempEndDateLabel = ref('')
const tempEndTimeLabel = ref('')

// 打开开始时间弹窗时动态赋值
watch(showStartTimePicker, (val) => {
  if (val) {
    tempStartDateLabel.value = dayjs(selectedDate.value).format('M月D日')
    tempStartTimeLabel.value = dayjs(selectedTime.value).format('HH:mm')
  }
})
// 切换Tab时动态赋值
watch([selectedDate, selectedTime, activePickerTab], () => {
  tempStartDateLabel.value = dayjs(selectedDate.value).format('M月D日')
  tempStartTimeLabel.value = dayjs(selectedTime.value).format('HH:mm')
})
// 打开结束时间弹窗时动态赋值
watch(showEndTimePicker, (val) => {
  if (val) {
    tempEndDateLabel.value = dayjs(selectedEndDate.value).format('M月D日')
    tempEndTimeLabel.value = dayjs(selectedEndTime.value).format('HH:mm')
  }
})
watch([selectedEndDate, selectedEndTime, activeEndPickerTab], () => {
  tempEndDateLabel.value = dayjs(selectedEndDate.value).format('M月D日')
  tempEndTimeLabel.value = dayjs(selectedEndTime.value).format('HH:mm')
})

// 日期选择年份
const dateYear = ref<number>(selectedDate.value.year())
const dateMonth = ref<number>(selectedDate.value.month() + 1)
const endDateYear = ref<number>(selectedEndDate.value.year())
const endDateMonth = ref<number>(selectedEndDate.value.month() + 1)

// 时间滚轮小时/分钟列表（数字数组）
const hourList: number[] = Array.from({ length: 24 }, (_, i) => i)
const minuteList: number[] = Array.from({ length: 12 }, (_, i) => i * 5) // 0,5,10,...,55

// 日历天数生成（以当前月为例，实际可根据需要生成）
function getCalendarDays(year: number, month: number, selected: dayjs.Dayjs) {
  const daysInMonth = dayjs(`${year}-${month}-01`).daysInMonth()
  const firstDayOfWeek = dayjs(`${year}-${month}-01`).day() // 0=周日, 1=周一...
  const days: any[] = []

  // 补前置空白
  for (let i = 0; i < firstDayOfWeek; i++) {
    days.push({
      day: null,
      isCurrent: false,
      isDisabled: true,
      isSelected: false
    })
  }

  // 填充本月天数
  for (let d = 1; d <= daysInMonth; d++) {
    days.push({
      day: d,
      isCurrent: selected.date() === d && selected.month() + 1 === month && selected.year() === year,
      isDisabled: false,
      isSelected: selected.date() === d && selected.month() + 1 === month && selected.year() === year
    })
  }
  return days
}

const calendarDays = ref(getCalendarDays(selectedDate.value.year(), selectedDate.value.month() + 1, selectedDate.value))
const endCalendarDays = ref(getCalendarDays(selectedEndDate.value.year(), selectedEndDate.value.month() + 1, selectedEndDate.value))

// 时间选择相关变量
const timeHour = ref(selectedTime.value.hour())
const timeMinute = ref(selectedTime.value.minute())
const endTimeHour = ref(selectedEndTime.value.hour())
const endTimeMinute = ref(selectedEndTime.value.minute())

// 打开开始时间弹窗时同步 hour/minute
watch(showStartTimePicker, (val) => {
  if (val) {
    timeHour.value = selectedTime.value.hour()
    timeMinute.value = selectedTime.value.minute()
  }
})
// 打开结束时间弹窗时同步 hour/minute
watch(showEndTimePicker, (val) => {
  if (val) {
    endTimeHour.value = selectedEndTime.value.hour()
    endTimeMinute.value = selectedEndTime.value.minute()
  }
})

// 1. 新增 loading 状态
const editLoading = ref(false)

const meetingRoomList = ref<any[]>([])
const fetchMeetingRoomList = async () => {
  try {
    // 拉取全部会议室（如有分页可调整）
    const res = await listMeetingRoom({ page: 1, size: 100, name: undefined, sort: [] })
    if (String(res.code) === '0') {
      meetingRoomList.value = res.data?.list || res.data || []
    }
  } catch (e) {
    meetingRoomList.value = []
  }
}

// 选择会议室
const selectRoom = (room: any) => {
  selectedRoomName.value = room.name
  formData.value.meetRoomId = room.id
  showRoomSelectModal.value = false
}

// 会议室选择相关变量
const factoryList = ref<any[]>([])
const buildingList = ref<any[]>([])
const floorList = ref<any[]>([])
const selectedFactoryId = ref('')
const selectedBuildingId = ref('')
const selectedFloor = ref('')
const tempSelectedRoomId = ref('')

// 拉取厂区
const fetchFactories = async () => {
  try {
    const res = await getFactoryList()
    factoryList.value = res || []
  } catch (e) {
    factoryList.value = []
  }
}
// 拉取办公楼
const onFactoryChange = async () => {
  selectedBuildingId.value = ''
  selectedFloor.value = ''
  buildingList.value = []
  floorList.value = []
  meetingRoomList.value = []
  if (selectedFactoryId.value) {
    try {
      buildingList.value = await getBuildingList(Number(selectedFactoryId.value))
    } catch (e) {
      buildingList.value = []
    }
  }
}
// 拉取楼层
const onBuildingChange = async () => {
  selectedFloor.value = ''
  floorList.value = []
  meetingRoomList.value = []
  if (selectedBuildingId.value) {
    try {
      const res = await getAvailableFloor(Number(selectedBuildingId.value))
      if (String(res.code) === '0' && res.success) {
        floorList.value = res.data.map((item: any) => item.floor)
      }
    } catch (e) {
      floorList.value = []
    }
  }
}
// 拉取会议室
const fetchMeetingRooms = async () => {
  if (!formData.value.startTime || !formData.value.length) return
  try {
    meetingRoomList.value = await getAvailableRooms({
      buildingId: selectedBuildingId.value ? Number(selectedBuildingId.value) : 0,
      floor: selectedFloor.value || '',
      factoryId: selectedFactoryId.value ? Number(selectedFactoryId.value) : 0,
      startTime: formData.value.startTime,
      continuedTime: formData.value.length
    })
  } catch (e) {
    meetingRoomList.value = []
  }
}
// 监听时间、时长、楼层变化自动刷新会议室列表
watch([() => formData.value.startTime, () => formData.value.length, selectedFactoryId, selectedBuildingId, selectedFloor], async () => {
  if (selectedFactoryId.value || selectedBuildingId.value || selectedFloor.value) {
    await fetchMeetingRooms()
  }
})

// 1. setup 顶部声明 customRuleDescription、showCustomRecurrenceModal
const customRuleDescription = ref('')
const showCustomRecurrenceModal = ref(false)

// 5. 确认自定义周期
function onCustomRecurrenceConfirm() {
  // 过滤 point，防止混入错误数据
  if (cycleParams.value.cycle === 'Week') {
    cycleParams.value.point = cycleParams.value.point.filter((d) => d >= 0 && d <= 6)
  } else if (cycleParams.value.cycle === 'Month') {
    cycleParams.value.point = cycleParams.value.point.filter((d) => d >= 1 && d <= 31)
  }
  // 生成描述
  let desc = ''
  if (cycleParams.value.cycle === 'Week') {
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    desc = `每${cycleParams.value.interval > 1 ? cycleParams.value.interval : ''}周的${cycleParams.value.point.map((p) => weekDays[p]).join('、')}重复`
  } else if (cycleParams.value.cycle === 'Month') {
    desc = `每${cycleParams.value.interval > 1 ? cycleParams.value.interval : ''}月的${cycleParams.value.point.map((p) => `${p}日`).join('、')}重复`
  } else if (cycleParams.value.cycle === 'Day') {
    desc = `每${cycleParams.value.interval > 1 ? cycleParams.value.interval : ''}天重复`
  }
  customRuleDescription.value = desc
  recurrenceType.value = 'custom-rule'
  formData.value.isRecurring = true
  formData.value.cycleParams = { ...cycleParams.value }
  showCustomRecurrenceModal.value = false
}

// 保证 cycleParams 和 formData.value.cycleParams 实时同步（单向）
watch(cycleParams, (val) => {
  formData.value.cycleParams = { ...val }
}, { deep: true })

// 获取默认开始日期，优先用会议原始开始时间
const getDefaultStartDate = () => {
  if (meetingInfo.value && meetingInfo.value.startTime) {
    return dayjs(meetingInfo.value.startTime).format('YYYY-MM-DD')
  }
  if (formData.value.startDate) {
    return formData.value.startDate
  }
  return dayjs().format('YYYY-MM-DD')
}

// 监听表单开始日期变化，自动同步到周期参数
watch(() => formData.value.startDate, (val) => {
  if (val) {
    cycleParams.value.startDate = val
  }
})

// 新增：打开开始时间弹窗时同步 selectedDate
const openStartTimePicker = () => {
  selectedDate.value = formData.value.startDate
    ? dayjs(formData.value.startDate)
    : dayjs()
  showStartTimePicker.value = true
}

// 切换到上一个月
const prevMonth = () => {
  selectedDate.value = selectedDate.value.subtract(1, 'month')
  dateYear.value = selectedDate.value.year()
  dateMonth.value = selectedDate.value.month() + 1
  calendarDays.value = getCalendarDays(dateYear.value, dateMonth.value, selectedDate.value)
}
// 切换到下一个月
const nextMonth = () => {
  selectedDate.value = selectedDate.value.add(1, 'month')
  dateYear.value = selectedDate.value.year()
  dateMonth.value = selectedDate.value.month() + 1
  calendarDays.value = getCalendarDays(dateYear.value, dateMonth.value, selectedDate.value)
}
</script>

<style lang="less" scoped>
.meeting-detail {
  height: 100vh;
  background-color: #fff;
  display: flex;
  flex-direction: column;

  .header {
    height: 50px;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 0 15px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    position: relative;

    .title {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      font-size: 16px;
      font-weight: 500;
    }
  }

  .content {
    flex: 1;
    overflow-y: auto;
    padding: 15px;

    .meeting-info {
      background-color: #fff;
      border-radius: 8px;
      padding: 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

      .info-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .name {
          font-size: 18px;
          font-weight: 500;
          flex: 1;
        }

        .status {
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;

          &.status-0 {
            background-color: #e6f7ff;
            color: #1890ff;
          }

          &.status-1 {
            background-color: #f6ffed;
            color: #52c41a;
          }

          &.status-2 {
            background-color: #f5f5f5;
            color: #5c5c5c;
          }

          &.status-3 {
            background-color: #fff2f0;
            color: #ff4d4f;
          }
        }
      }

      .info-item {
        margin-bottom: 12px;

        .item-label {
          color: #8c8c8c;
          font-size: 14px;
          margin-bottom: 4px;
        }

        .item-value {
          font-size: 15px;
        }
      }

      .action-buttons {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 20px;

        .arco-btn {
          flex: 1;
          min-width: 120px;
        }
      }
    }

    .no-data {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 300px;
    }
  }
}

.link-icon {
  width: 16px;
  height: 16px;
}

.mobile-detail {
  background: #fff;
  min-height: 100vh;
  .mobile-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 18px 16px 8px 16px;
    .mobile-header-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      margin-bottom: 4px;
    }
    .mobile-back-btn {
      margin-right: 8px;
      padding: 0;
      min-width: 32px;
      color: #222;
      background: none;
      border: none;
      box-shadow: none;
      font-size: 20px;
      display: flex;
      align-items: center;
      .back-svg {
        width: 22px;
        height: 22px;
        display: block;
      }
    }
    .subject {
      font-size: 20px;
      font-weight: bold;
      color: #222;
      width: 100%;
      text-align: left;
      margin: 0 0 4px 0;
      padding: 0 16px;
    }
    .subject-center {
      display: block;
    }
    .mobile-header-menu {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 100%;
      margin-bottom: 4px;
    }
    .menu-btn {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background: none;
      cursor: pointer;
      .more-vertical-svg {
        width: 22px;
        height: 22px;
        display: block;
      }
    }
  }
  .subject {
    font-size: 20px;
    font-weight: bold;
    color: #222;
    width: 100%;
    text-align: left;
    margin: 0 0 4px 0;
    padding: 0 16px;
  }
  .subject-center {
    display: block;
  }
  .mobile-title {
    margin-bottom: 18px;
  }
  .mobile-content {
    padding: 18px 16px 0 16px;
    .row {
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      font-size: 16px;
    }
    .cycle-info-row {
      margin-bottom: 20px;
      font-size: 14px;
      color: #666;
      line-height: 1.5;
    }
    .time-row {
      color: #2E71FF;
      font-weight: 500;
    }
    .creator-row {
      .creator-label {
        color: #888;
        margin-right: 4px;
      }
      .avatar {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        margin-right: 4px;
        object-fit: cover;
        vertical-align: middle;
      }
      .creator-name {
        font-weight: 500;
        color: #333;
        font-size: 15px;
        margin-right: 8px;
        vertical-align: middle;
      }
    }
    .participants-row {
      color: #666;
      font-size: 15px;
      span:first-child {
        margin-right: 4px;
      }
      .participants-label {
        color: #888;
        margin-right: 4px;
      }
      .participant-avatar {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        margin-right: 4px;
        object-fit: cover;
        vertical-align: middle;
      }
      .participant-name {
        margin-right: 8px;
        color: #333;
        font-size: 15px;
        vertical-align: middle;
        font-weight: 500;
      }
      .arrow-icon {
        color: #2E71FF;
        margin-left: 4px;
        vertical-align: middle;
        .participants-total {
          color: #888;
          font-size: 14px;
          margin-left: 4px;
          vertical-align: middle;
        }
      }
    }
    .btn-row {
      display: flex;
      gap: 12px;
      margin-top: 24px;
      .vertical-btn {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 64px;
        font-size: 15px;
        border: none;
        box-shadow: none;
        padding: 0;
      }
      .copy-btn {
        background: #f5f5f5;
        color: #222;
      }
      .join-btn {
        background: #e6f0ff;
        color: #2E71FF;
      }
      .btn-icon-wrap {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 4px;
        font-size: 22px;
      }
      .btn-text {
        font-size: 15px;
        line-height: 1.2;
      }
    }
  }
}

.participants-modal-list {
  max-height: 300px;
  overflow-y: auto;
  .modal-participant-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    .participant-avatar {
      width: 28px;
      height: 28px;
      margin-right: 8px;
    }
    .participant-name {
      color: #333;
      font-size: 16px;
    }
  }
}

.location-info-row {
  font-size: 15px;
  color: #333;
  padding: 0 0 12px 0;
  .location-label {
    color: #888;
    margin-right: 4px;
  }
  .location-value {
    color: #333;
  }
}

.a-dropdown .a-doption.danger {
  color: #ff4d4f;
}

// 移动端子会议管理样式
.mobile-sub-meeting-list {
  max-height: 60vh;
  overflow-y: auto;

  .mobile-sub-meeting-item {
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .sub-meeting-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 8px;

      .sub-meeting-title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        flex: 1;
        margin-right: 12px;
        line-height: 1.4;
      }

      .sub-meeting-actions {
        display: flex;
        gap: 8px;
        flex-shrink: 0;

        .arco-btn {
          min-width: 48px;
          height: 32px;
          font-size: 14px;
        }
      }
    }

    .sub-meeting-info {
      .sub-meeting-time {
        font-size: 14px;
        color: #666;
        margin-bottom: 4px;
      }

      .sub-meeting-promoter {
        font-size: 14px;
        color: #888;
      }
    }
  }
}

.no-sub-meetings {
  padding: 40px 0;
  text-align: center;
}

.mobile-edit-sub-form {
  .form-item {
    margin-bottom: 20px;

    .form-label {
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .arco-input,
    .arco-input-number,
    .arco-picker {
      height: 44px;
      border-radius: 8px;
      border: 1px solid #e8e8e8;

      &:focus,
      &:hover {
        border-color: #2E71FF;
      }
    }
  }
}

/* 移动端编辑会议弹窗样式 */
.mobile-schedule-modal-wrap {
  z-index: 1000;
}

.mobile-schedule-modal-wrap :deep(.arco-modal) {
  max-height: 90vh;
  margin: 5vh auto;
}

.mobile-schedule-modal-wrap :deep(.arco-modal-body) {
  max-height: 70vh;
  overflow-y: auto;
  padding: 16px;
}

.mobile-schedule-content {
  width: 100%;
}

/* 新增水平布局表单样式 */
.mobile-form-row {
  display: flex;
  align-items: center;
  padding: 12px 16px;

  .form-label {
    width: 48px;
    font-size: 14px;
    color: #333;
    flex-shrink: 0;
  }

  .mobile-attendees-bar {
    flex: 1;
    margin-left: 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    background: #f8f9fa;
    border-radius: 6px;
    cursor: pointer;
    border: 1px solid #e0e6ed;
    min-height: 48px;

    .attendees-avatars {
      display: flex;
      align-items: center;
      gap: 8px;

      .attendee-avatar {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .attendees-ellipsis {
        font-size: 14px;
        color: #666;
      }

      .placeholder-text {
        color: #999;
        font-size: 14px;
      }
    }
  }

  .mobile-start-time-wrapper-left {
    flex: 1;
    margin-left: 12px;
    background: white;
    border-radius: 4px;
    padding: 6px 8px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 6px;
  }

  .mobile-duration-wrapper-left {
    flex: 1;
    margin-left: 12px;
    padding: 6px 8px;
    background: white;
    border-radius: 4px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 6px;

    .duration-value {
      color: #333;
      font-size: 13px;
    }
  }

  .mobile-location-input {
    flex: 1;
    margin-left: 12px;
    padding: 6px 8px;
    background: white;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;

    .location-value {
      color: #333;
      font-size: 13px;
    }

    .location-placeholder {
      color: #999;
      font-size: 13px;
    }
  }

  .select-wrapper {
    flex: 1;
    margin-left: 12px;
  }

  .setting-wrapper {
    flex: 1;
    margin-left: 12px;
  }
}

/* 主题输入框样式 */
.subject-row-full {
  padding: 16px 16px 12px 16px;
  background: transparent;

  .subject-input-native {
    width: 100%;
    border: none;
    outline: none;
    background: transparent;
    font-size: 18px;
    font-weight: 400;
    padding: 8px 0;
    min-height: 40px;
    color: #333;
    font-family: inherit;

    &::placeholder {
      color: #999;
      font-size: 18px;
      font-weight: 400;
    }

    &:focus {
      outline: none;
      border: none;
      background: transparent;
    }
  }
}

/* 分隔线样式 */
.form-divider {
  height: 1px;
  background: #f5f5f5;
  margin: 0 16px;
}

/* 开始时间灰色块样式 */
.mobile-date-block-gray,
.mobile-time-block-gray {
  display: inline-block;
  padding: 4px 6px;
  background: #f5f5f5;
  border: none;
  border-radius: 3px;
  color: #333;
  font-size: 12px;
  cursor: pointer;
  margin-right: 4px;
  min-width: 45px;
  text-align: center;
  white-space: nowrap;
  line-height: 1.2;

  &:last-child {
    margin-right: 0;
  }

  &:hover {
    background: #e8e8e8;
  }
}

/* 底部按钮样式 */
.mobile-form-footer {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.mobile-bottom-buttons {
  display: flex;
  gap: 12px;
  padding: 12px 16px;

  .mobile-cancel-btn,
  .mobile-confirm-btn {
    flex: 1;
    height: 44px;
    font-size: 15px;
    font-weight: 500;
    border-radius: 6px;
  }

  .mobile-cancel-btn {
    background: #f5f5f5;
    border: none;
    color: #666;

    &:hover {
      background: #e8e8e8;
    }
  }

  .mobile-confirm-btn {
    background: #1890ff;
    border: none;

    &:hover {
      background: #40a9ff;
    }
  }
}

/* 时长选择弹窗样式 */
.duration-options {
  padding: 8px 0;
  max-height: 400px;
  overflow-y: auto;

  .duration-option {
    padding: 12px 16px;
    cursor: pointer;
    font-size: 15px;
    color: #333;
    border-radius: 4px;
    margin: 2px 0;

    &:hover {
      background: #f5f5f5;
    }

    &.selected {
      background: #e6f7ff;
      color: #1890ff;
    }
  }
}

/* 会议设置弹窗样式 */
.mobile-setting-section {
  .mobile-setting-row {
    margin-bottom: 16px;

    .setting-label {
      display: block;
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .arco-select,
    .arco-input {
      width: 100%;
    }

    .arco-checkbox {
      font-size: 14px;
    }
  }
}

/* 参会人选择弹窗样式 */
.mobile-user-selector-modal-wrap {
  :deep(.arco-modal) {
    max-height: 85vh !important;
    margin: 7.5vh auto !important;
    max-width: 90vw !important;
  }

  :deep(.arco-modal-body) {
    padding: 16px !important;
    max-height: 70vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
}

.user-selector-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .modal-search-results {
    max-height: 200px;
    overflow-y: auto;
    margin-bottom: 16px;
    border: 1px solid #e8e8e8;
    border-radius: 6px;
    background: #fafafa;
  }

  .search-result-item {
    display: flex;
    align-items: center;
    padding: 12px;
    cursor: pointer;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background: #f5f5f5;
    }

    .user-option-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      margin: 0 12px;
      object-fit: cover;
    }

    span {
      font-size: 14px;
      color: #333;
    }
  }

  .invite-tree {
    flex: 1;
    min-height: 200px;

    :deep(.arco-tree-node) {
      padding: 4px 0;
    }

    :deep(.arco-tree-node-title) {
      font-size: 14px;
    }
  }
}

.selected-users-preview {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
  margin-top: 16px;

  .selected-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 12px;
    font-weight: 500;
  }

  .selected-users-avatars {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    max-height: 120px;
    overflow-y: auto;
  }

  .selected-avatar-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 60px;
    transition: all 0.2s ease;

    &.clickable {
      cursor: pointer;

      &:hover {
        transform: scale(0.95);

        .avatar-wrapper .remove-overlay {
          opacity: 1;
        }
      }
    }

    .avatar-wrapper {
      position: relative;
      margin-bottom: 4px;

      img {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        object-fit: cover;
        transition: all 0.2s ease;
      }

      .remove-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.2s ease;

        .remove-icon {
          color: white;
          font-size: 14px;
        }
      }
    }

    .user-name {
      font-size: 12px;
      color: #666;
      text-align: center;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 100%;
    }

    &.clickable:hover .user-name {
      color: #f56565;
    }
  }
}

.user-selector-footer {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
  margin-top: 16px;
  flex-shrink: 0;
}

/* 开始时间底部弹窗样式 */
.mobile-bottom-picker-mask {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  background: rgba(0,0,0,0.4);
  z-index: 9999;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  pointer-events: auto;
}
.mobile-bottom-picker-new {
  width: 100%;
  background: #fff;
  border-radius: 16px 16px 0 0;
  box-shadow: 0 -2px 8px rgba(0,0,0,0.08);
  padding-bottom: 16px;
}

.picker-header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 16px 16px 0 0;
  padding: 12px 16px 0 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
}
.picker-tabs-bar {
  display: flex;
  background: #f7f8fa;
  border-radius: 16px;
  overflow: hidden;
  flex: 1;
  margin: 0 12px;
}
.picker-tab-bar {
  flex: 1;
  text-align: center;
  padding: 8px 0 6px 0;
  font-size: 16px;
  color: #888;
  background: #f7f8fa;
  cursor: pointer;
  transition: all 0.2s;
}
.picker-tab-bar.active {
  background: #fff;
  color: #1677ff;
  font-weight: 500;
}
.picker-confirm-bar {
  color: #1677ff;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  margin-left: 8px;
}
.picker-content-bar {
  padding: 0 0 0 0;
}
.calendar-bar {
  padding: 0;
}
.calendar-bar-header {
  text-align: center;
  font-size: 15px;
  color: #333;
  margin: 12px 0 8px 0;
}
.calendar-bar-week,
.calendar-bar-days {
  width: 100%;
  margin: 0;
  padding: 0;
}
.calendar-bar-week {
  display: flex;
  justify-content: space-between;
  color: #bbb;
  font-size: 13px;
  margin-bottom: 4px;
}
.calendar-bar-days {
  display: flex;
  flex-wrap: wrap;
  gap: 0;
}
.calendar-day {
  width: calc(100% / 7);
  min-width: 0;
  box-sizing: border-box;
  text-align: center;
  padding: 6px 0;
  font-size: 15px;
  color: #333;
  border-radius: 50%;
  cursor: pointer;
  margin-bottom: 2px;
  transition: background 0.2s, color 0.2s;
}
.calendar-day.current {
  border: 1.5px solid #1677ff;
}
.calendar-day.selected {
  background: #1677ff;
  color: #fff;
}
.calendar-day.disabled {
  color: #ccc;
  background: none;
  cursor: not-allowed;
}
.calendar-day.empty {
  background: none;
  cursor: default;
  color: transparent;
  pointer-events: none;
}
.time-scroll-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 24px;
  padding: 32px 0 0 0;
}
.time-scroll-col {
  width: 60px;
  height: 160px;
  overflow-y: auto;
  background: #f7f8fa;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  scrollbar-width: none;
}
.time-scroll-list {
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
}
.time-scroll-item {
  text-align: center;
  font-size: 20px;
  color: #333;
  padding: 10px 0;
  cursor: pointer;
  border-radius: 8px;
  transition: background 0.2s, color 0.2s;
}
.time-scroll-item.selected {
  background: #1677ff;
  color: #fff;
  font-weight: 500;
}
.time-scroll-item.disabled {
  color: #ccc !important;
  background: #f5f5f5 !important;
  cursor: not-allowed !important;
}

.mobile-rooms-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 8px;
}
.mobile-room-card {
  padding: 8px !important;
  border-radius: 8px !important;
  align-items: center !important;
}
.mobile-room-card .room-image {
  width: 50px !important;
  height: 50px !important;
  margin-right: 12px !important;
}
.mobile-room-card .room-info .room-name {
  font-size: 14px !important;
}
.mobile-room-card .room-info .room-capacity {
  font-size: 12px !important;
}

.custom-recurrence-modal-content {
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.custom-recurrence-modal-content :deep(.arco-form-item) {
  margin-bottom: 20px;
}

.custom-recurrence-modal-content :deep(.arco-form-item-label) {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.custom-recurrence-modal-content :deep(.arco-input-number) {
  width: 100%;
}

.custom-recurrence-modal-content :deep(.arco-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.custom-recurrence-modal-content :deep(.arco-checkbox) {
  font-size: 14px;
}

.custom-recurrence-modal-content :deep(.arco-button) {
  width: 100%;
}

.calendar-day.empty {
  background: none;
  cursor: default;
  color: transparent;
  pointer-events: none;
}
</style>
